package com.bobbygu.server.simpleapp.controller;

import com.bobbygu.server.simpleapp.mapper.AppLogMapper;
import com.bobbygu.server.simpleapp.model.response.BaseResponse;
import com.bobbygu.server.simpleapp.model.response.ConstResponse;
import com.bobbygu.server.simpleapp.model.response.ResultResponse;
import com.bobbygu.server.simpleapp.model.response.StringResponse;
import com.bobbygu.server.simpleapp.utils.SafeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Map;

@RestController
public class AppLogController {
    @SuppressWarnings("SpringJavaAutowiringInspection")
    @Autowired
    private AppLogMapper appLogMapper;

    /**
     * 上传app日志
     *
     * @param requestMap 上传数据
     * @return
     * @throws NoSuchAlgorithmException
     */
    @RequestMapping(value = "/home/UploadAppLog.do", method = RequestMethod.POST)
    public BaseResponse uploadAppLog(@RequestBody Map<String, Object> requestMap) throws NoSuchAlgorithmException {
        System.out.println("UploadAppLog.do");
        if (requestMap.get("TagName") == null) {
            return new BaseResponse("TagName 不能为空", ConstResponse.STATUS_PARAM_ERROR);
        }
        if (requestMap.get("LogType") == null) {
            return new BaseResponse("LogType 不能为空", ConstResponse.STATUS_PARAM_ERROR);
        }
        if (requestMap.get("CreateTime") == null) {
            return new BaseResponse("CreateTime 不能为空", ConstResponse.STATUS_PARAM_ERROR);
        }
        if (requestMap.get("Content") == null) {
            return new BaseResponse("Content 不能为空", ConstResponse.STATUS_PARAM_ERROR);
        }

        String tagName = requestMap.get("TagName").toString();
        String logType = requestMap.get("LogType").toString();
        String createTime = requestMap.get("CreateTime").toString();
        String content = requestMap.get("Content").toString();

        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(System.currentTimeMillis());
        String token = SafeUtil.MD5("app" + createTime + random.nextDouble());

        appLogMapper.insertAppLog(tagName, logType, createTime, content, token);
        return new ResultResponse(new StringResponse("上传成功"), ConstResponse.DESC_OK, ConstResponse.STATUS_OK);
//        return new BaseResponse(ConstResponse.DESC_OK, ConstResponse.STATUS_OK);
    }

    @RequestMapping(value = "/home/ShowAppLogList.do", method = RequestMethod.POST)
    public BaseResponse showAppLogList() {
        System.out.println("ShowAppLogList");
        return new ResultResponse(appLogMapper.selectAll(), ConstResponse.DESC_OK, ConstResponse.STATUS_OK);
    }
}
